package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-01
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    /**
     * 根据url  找到id
     * @param url
     * @return
     */
    @Override
    public WmMaterial findAllByUrl(String url) {
        if (StringUtils.isEmpty(url)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmMaterial::getUrl,url);
        WmMaterial material = this.getOne(lqw);
        return material;
    }

    /**
     * 素材分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult pageList(WmMaterialDto dto) {
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();

        lqw.eq(WmMaterial::getUserId, UserThreadLocalUtils.getUserId());

        if (dto.getIsCollection() != null && dto.getIsCollection() == 1){
            lqw.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        lqw.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> materialPage = new Page<>(dto.getPage(),dto.getSize());
        Page<WmMaterial> page = this.page(materialPage, lqw);
        if (CollectionUtils.isEmpty(page.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return new PageResult(dto.getPage(), dto.getSize(), page.getTotal(),page.getRecords());
    }

    @Autowired
    private MinioService minioService;
    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult<String> upload(MultipartFile multipartFile) {
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId == null){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        };
        //后缀
        String suffix = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), ".");
        String newFileName = UUID.randomUUID() + "."+suffix;
        String url = null;
        try {
            url = minioService.uploadImgFile(""
                    , newFileName, multipartFile.getInputStream());
        } catch (Exception e){
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(url);
        wmMaterial.setType(0);
        wmMaterial.setUserId(userId);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        boolean save = this.save(wmMaterial);
        if (!save){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        return ResponseResult.ok(url);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Long id) {

        if (id == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        this.removeById(id);
        return ResponseResult.ok();


    }
    /**
     * 添加收藏
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult collect(Long id) {
        WmMaterial material = this.getById(id);
        material.setIsCollection(true);
        this.updateById(material);
        return ResponseResult.ok();
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Long id) {
        WmMaterial material = this.getById(id);
        material.setIsCollection(false);
        this.updateById(material);
        return ResponseResult.ok();
    }
}
